import curses
import random

def initMap(ysize, xsize, p):
	m = [[]   for i in range(ysize)]
	for x in range(xsize):
		m[0].append(0)
	for y in range(1,ysize-1):
		m[y].append(0)
		for x in range(1,xsize-1):
			m[y].append(random.random() < p)
		m[y].append(0)
	for x in range(xsize):
		m[ysize-1].append(0)
	return m		

def dispMap(scr,m):
	for y in range(len(m)):
		for x in range(len(m[y])):
			if m[y][x]:
				scr.addch(y,x,ord('.'))
			else:
				scr.addch(y,x,ord('#'))
	scr.refresh()			

def wallcount(m,y,x):
	count = 0
	for dy in (-1,0,1):
		for dx in (-1,0,1):
			if not(m[y+dy][x+dx]):
				count = count + 1
	return count

def evolvemap(m):
	for y in range(1,len(m)-1):
		for x in range(1,len(m[y])-1):
			w = wallcount(m,y,x)
			if m[y][x] and w > 5:
				m[y][x] = 0
			elif not(m[y][x]) and w < 4:
				m[y][x] = 1
	return m

		
def main(scr):
	ymax, xmax = scr.getmaxyx()
	m = initMap(ymax-1,xmax,0.50)
	for i in range(2):
		m = evolvemap(m)
	cy,cx = ymax/2,xmax/2
	while not(m[cy][cx]):
		cy,cx = cy-1,cx-1
	dispMap(scr,m)
	scr.addch(cy,cx,ord('@'))
	scr.move(cy,cx)
	while 1:
		c = scr.getch()
		if c == curses.KEY_UP and cy > 0 and m[cy-1][cx]: cy = cy-1
		elif c == curses.KEY_DOWN and cy < ymax-1 and m[cy+1][cx]: cy = cy+1
		elif c == curses.KEY_LEFT and cx > 0 and m[cy][cx-1]: cx = cx-1
		elif c == curses.KEY_RIGHT and cx < xmax-1 and m[cy][cx+1]: cx = cx+1
		elif c == ord('q'): return
		dispMap(scr,m)
		scr.addch(cy,cx,ord('@'))
		scr.move(cy,cx)
		
curses.wrapper(main)
